package com.cskaoyan.service.wx.coupon;

import com.cskaoyan.bean.BaseParam;
import com.cskaoyan.bean.cart.Cart;
import com.cskaoyan.bean.cart.CartExample;
import com.cskaoyan.bean.goods.MarketGoods;
import com.cskaoyan.bean.promotion.coupon.Coupon;
import com.cskaoyan.bean.promotion.coupon.CouponExample;
import com.cskaoyan.bean.promotion.coupon.CouponUser;
import com.cskaoyan.bean.promotion.coupon.CouponUserExample;
import com.cskaoyan.bean.user.User;
import com.cskaoyan.bean.wx_coupon.*;
import com.cskaoyan.mapper.CartMapper;
import com.cskaoyan.mapper.CouponMapper;
import com.cskaoyan.mapper.CouponUserMapper;
import com.cskaoyan.mapper.goodsMapper.MarketGoodsMapper;
import com.cskaoyan.util.PageUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @Description:
 * @Author: WD created on 2021-09-19 12:36
 * @Version:
 */

@Service
public class WXCouponServiceImpl implements WXCouponService {
    @Autowired
    CouponUserMapper couponUserMapper;
    @Autowired
    CouponMapper couponMapper;
    @Autowired
    CartMapper cartMapper;
    @Autowired
    MarketGoodsMapper goodsMapper;


    @Override
    public WXShowMyListCouponVO getMyCouponList(BaseParam baseParam, Integer id, Integer status) {
        PageUtil.start(baseParam);
        CouponUserExample couponUserExample = new CouponUserExample();
        CouponUserExample.Criteria criteria = couponUserExample.createCriteria();
        criteria.andUserIdEqualTo(id);
        criteria.andStatusEqualTo(status.shortValue());
        criteria.andDeletedEqualTo(false);
        List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);
        PageInfo<CouponUser> couponUserPageInfo = new PageInfo<>(couponUsers);
        ArrayList<WXMyListInnerCoupon> userCoupons = new ArrayList<>();

        for (CouponUser couponUser : couponUsers) {
            Integer couponId = couponUser.getCouponId();
            //判断是否过期
            if (couponUser.getStatus() == 0 && couponUser.getEndTime() != null && couponUser.getEndTime().getTime() <= new Date().getTime()) {
                //过期
                couponUserMapper.updateStatusByCouponId(couponId);
                couponMapper.UpdateStatusById(couponId);
                couponUser.setStatus((short) 2);
                continue;
            }
            Coupon coupon = couponMapper.selectByPrimaryKey(couponId);
            userCoupons.add(new WXMyListInnerCoupon(coupon, couponUser.getId(), couponUser.getDeleted()));
        }

        return new WXShowMyListCouponVO(couponUserPageInfo, userCoupons);


    }

    @Override
    public Integer exchangeByCode(String code, User user) {
        Integer uid = user.getId();
        //判断code是否正确
        CouponExample couponExample = new CouponExample();
        CouponExample.Criteria criteria = couponExample.createCriteria();
        criteria.andCodeEqualTo(code);
        criteria.andTypeEqualTo((short) 2);
        List<Coupon> coupons = couponMapper.selectByExample(couponExample);
        if (coupons.size() == 0) {
            //code错误
            return 404;
        }
        Coupon coupon = coupons.get(0);
        Integer cid = coupon.getId();
        //是否过期
        if (coupon.getEndTime().getTime() <= new Date().getTime()) {
            Integer id = coupon.getId();
            couponMapper.UpdateStatusById(id);
            couponUserMapper.updateStatusByCouponId(id);
            //过期
            return 402;
        }

        //检查当前库存(total为0无限量)
        if (coupon.getTotal() != 0) {
            Integer currentNum = couponMapper.getCurrentNum(cid);
            if (currentNum <= 0) {
                //以被灵光
                return 401;
            }
        }
        //检查当前用户是否领取超出上限
        //限领数量
        Short limit = coupon.getLimit();
        CouponUserExample couponUserExample = new CouponUserExample();
        CouponUserExample.Criteria userExampleCriteria = couponUserExample.createCriteria();
        userExampleCriteria.andCouponIdEqualTo(cid).andUserIdEqualTo(uid).andDeletedEqualTo(false);
        List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);

        if (couponUsers.size() >= limit) {
            //领取超出数量限制
            return 405;
        }
        //正式开始流程
        CouponUser couponUser = new CouponUser(coupon, uid);
        int i = couponUserMapper.insertSelective(couponUser);
        if (i != 1) {
            //未知错误
            return 400;
        }
        if (coupon.getTotal().equals(0)) {
            return 200;
        }
        Integer currentNum = couponMapper.getCurrentNum(cid);
        Integer resultNum = currentNum - 1;
        couponMapper.updateCurrentNum(resultNum, cid);

        return 200;
    }

    @Override
    public WXShowSelectCouponVO getSelectCoupon(Integer id) {

        BaseParam param = new BaseParam();
        param.setLimit(1000);
        param.setPage(1);
        PageUtil.start(param);


        CouponUserExample couponUserExample = new CouponUserExample();
        CouponUserExample.Criteria criteria = couponUserExample.createCriteria();
        criteria.andStatusEqualTo((short) 0).andDeletedEqualTo(false);
        List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);
        if (couponUsers.size() == 0) {
            return new WXShowSelectCouponVO();
        }
        //接收
        ArrayList<WXSelectInnerCoupon> wxSelectInnerCoupons = new ArrayList<>();
        for (CouponUser couponUser : couponUsers) {
            Integer couponId = couponUser.getCouponId();
            Coupon coupon = couponMapper.selectByPrimaryKey(couponId);
            wxSelectInnerCoupons.add(new WXSelectInnerCoupon(coupon,couponUser.getId(),true));
        }

        //订单相关数据
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria1 = cartExample.createCriteria();
        criteria1.andUserIdEqualTo(id).andDeletedEqualTo(false).andCheckedEqualTo(true);
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        //维持一个goodsidlist
        ArrayList<Integer> gids = new ArrayList<>();
        //维持一个categoriesIdList
        ArrayList<Integer> cids = new ArrayList<>();
        double sumMoney = (double) 0;
        for (Cart cart : carts) {

            Integer goodsId = cart.getGoodsId();
            gids.add(goodsId);
            MarketGoods goods = goodsMapper.selectByPrimaryKey(goodsId);
            cids.add(goods.getCategoryId());

            //订单总金额
            Short number = cart.getNumber();
            Double price = cart.getPrice().doubleValue();
            double money = number * price;
            sumMoney += money;
        }

        Iterator<WXSelectInnerCoupon> wxSelectInnerCouponIterator = wxSelectInnerCoupons.iterator();
//        Iterator<CouponUser> couponUserIterator = couponUsers.iterator();
        flag:
        while (wxSelectInnerCouponIterator.hasNext()) {
            //相关信息
            WXSelectInnerCoupon wxSelectInnerCoupon = wxSelectInnerCouponIterator.next();
            Integer couponUserId = wxSelectInnerCoupon.getId();
            CouponUser couponUser = couponUserMapper.selectByPrimaryKey(couponUserId);
            Integer couponId = couponUser.getCouponId();
            Coupon coupon = couponMapper.selectByPrimaryKey(couponId);

            Date endTime = couponUser.getEndTime();
            //检查是否有过期的
            if (endTime.getTime() <= new Date().getTime()) {
                wxSelectInnerCoupon.setAvailable(false);
                //更新状态
                couponUserMapper.updateStatusByCouponId(couponUser.getCouponId());
                couponMapper.UpdateStatusById(couponUser.getCouponId());
                continue;
            }
            //判断金额
            //金额
            if (sumMoney < coupon.getMin()) {
                //不满足最低消费需求
                wxSelectInnerCoupon.setAvailable(false);
                continue;
            }
            //类型
            Short goodsType = coupon.getGoodsType();

            if (goodsType == 0) {
                //全类型
                continue;
            }
            //商品类目或商品类型
            Integer[] goodsValue = coupon.getGoodsValue();
            if (goodsType == 1) {
                //类目限制
                for (Integer integer : goodsValue) {
                    if (!cids.contains(integer)) {
                        wxSelectInnerCoupon.setAvailable(false);
                        continue flag;
                    }
                }

            } else {
                //商品限制
                for (Integer integer : goodsValue) {
                    if (!gids.contains(integer)) {
                        wxSelectInnerCoupon.setAvailable(false);
                        continue flag;
                    }
                }
            }

        }


        PageInfo<CouponUser> couponUserPageInfo = new PageInfo<>(couponUsers);


        WXShowSelectCouponVO wxShowSelectCouponVO = new WXShowSelectCouponVO(couponUserPageInfo, wxSelectInnerCoupons);
        return wxShowSelectCouponVO;
    }

    @Override
    public WXShowCouponListVO getCouponList(BaseParam baseParam) {
        PageUtil.start(baseParam);
        CouponExample couponExample = new CouponExample();
        CouponExample.Criteria criteria = couponExample.createCriteria();
        criteria.andTypeEqualTo((short)1).andDeletedEqualTo(false).andStatusEqualTo((short)0);
        List<Coupon> coupons = couponMapper.selectByExample(couponExample);
        PageInfo<Coupon> couponPageInfo = new PageInfo<>(coupons);

        ArrayList<WXCouponListInnerCoupon> innerCoupons = new ArrayList<>();
        for (Coupon coupon : coupons) {
            innerCoupons.add(new WXCouponListInnerCoupon(coupon));
        }

        return new WXShowCouponListVO(couponPageInfo,innerCoupons);

    }

    @Override
    public Integer receive(Integer cid, Integer uid) {
        Coupon coupon = couponMapper.selectByPrimaryKey(cid);
        //是否过期
        if (coupon.getEndTime().getTime() <= new Date().getTime()) {
            Integer id = coupon.getId();
            couponMapper.UpdateStatusById(id);
            couponUserMapper.updateStatusByCouponId(id);
            //过期
            return 400;
        }

        //检查当前库存(total为0无限量)
        if (coupon.getTotal() != 0) {
            Integer currentNum = couponMapper.getCurrentNum(cid);
            if (currentNum <= 0) {
                //以被灵光
                return 401;
            }
        }

        //检查当前用户是否领取超出上限
        //限领数量
        Short limit = coupon.getLimit();
        CouponUserExample couponUserExample = new CouponUserExample();
        CouponUserExample.Criteria userExampleCriteria = couponUserExample.createCriteria();
        userExampleCriteria.andCouponIdEqualTo(cid).andUserIdEqualTo(uid).andDeletedEqualTo(false);
        List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);

        if (couponUsers.size() >= limit) {
            //领取超出数量限制
            return 405;
        }


        //正式开始流程
        CouponUser couponUser = new CouponUser(coupon, uid);
        int i = couponUserMapper.insertSelective(couponUser);
        if (i != 1) {
            //未知错误
            return 402;
        }



        if (coupon.getTotal().equals(0)) {
            //无限量不用管库存
            return 200;
        }
        Integer currentNum = couponMapper.getCurrentNum(cid);
        Integer resultNum = currentNum - 1;
        couponMapper.updateCurrentNum(resultNum, cid);

        return 200;

    }
}
